from PyQt5.QtCore import QThread, QSettings
from pyaudio import PyAudio
import wave
import os
import logging.config
import traceback
from util.Tools import Tools

settings = QSettings(Tools.resource_path("config\\config.ini"), QSettings.IniFormat)
settings.setIniCodec("UTF-8")


# TODO 语音播报
class Speech(QThread):
    def __init__(self):
        super(Speech).__init__()
        self.p = PyAudio()

        self.CHUNK = 1024

    def playSpeech(self, fileName):
        '''播报语音'''
        try:
            wf = wave.open(fileName, 'rb')
            stream = self.p.open(format=self.p.get_format_from_width(wf.getsampwidth()),
                                 channels=wf.getnchannels(), rate=wf.getframerate(),
                                 output=True)  # 打开数据流--【获取音频格式信息】
            # output=True   输出的意思
            data = wf.readframes(self.CHUNK)  # 读取数据
            while data != b'' and not (stream.is_stopped()):
                print("正在播放")
                # stream.is_stopped()  流是否停止，如果停止返回True
                stream.write(data)  # 播放
                data = wf.readframes(self.CHUNK)
            stream.stop_stream()
            stream.close()
            print("结束")
        except Exception:
            logging.error(traceback.format_exc())


obj = Speech()
fileName = "1.wav"
basepath = os.path.join(Tools.resource_path("downloadAudio"), fileName)

obj.playSpeech(basepath)
